<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="注册/登录"
      left-arrow
      @click-left="$router.back()"
    />

    <!-- 登录表单 -->
    <van-form
      @submit="onLogin"
      validate-first
      :show-error="false"
      :show-error-message="false"
      @failed="onFailed"
      ref="login-form"
    >
      <van-cell-group>
        <van-field
          v-model="user.mobile"
          icon-prefix="toutiao"
          left-icon="shouji"
          placeholder="请输入手机号"
          :rules="formRules.mobile"
          name="mobile"
        />
        <van-field
          v-model="user.code"
          clearable
          icon-prefix="toutiao"
          left-icon="yanzhengma"
          placeholder="请输入验证码"
          :rules="formRules.code"
          name="code"
        >
          <template #button>
            <van-count-down
              :time="1000 * 60"
              format="ss s"
              v-if="iscountDownshow"
              @finish="iscountDownshow = false"
            />
            <van-button
              size="small"
              round
              class="send-btn"
              v-else
              @click.prevent="onSendSms"
              :loading= 'issendSmsLoading'
              >发送验证码</van-button
            >
          </template>
        </van-field>
      </van-cell-group>

      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from "@/API/user";
// import {Toast} from "vant"
export default {
  name: "LoginContainer",
  data() {
    return {
      //登录信息
      user: {
        mobile:13911111111,
        code:246810,
      },
      formRules: {
        mobile: [
          { required: true, message: "请输入手机号" },
          { pattern: /^1[3|4|5|7|8|9]\d{9}$/, message: "手机号格式错误" },
        ],
        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /^\d{6}$/, message: "验证码错误" },
        ],
      },
      iscountDownshow: false,
      issendSmsLoading: false
    };
  },
  methods: {
    async onLogin() {
      this.$toast.loading({
        message: "登录中...",
        forbidClick: true,
        duration: 0,
      });
      try {
        const{data} = await login(this.user);
        this.$toast.success("登陆成功");
//将token放到vuex中
this.$store.commit('setUser',data.data)
this.$router.back()
      } catch (err) {
        if (err.response.status === 400) {
          console.log("登录失败", err);
          this.$toast.fail("登陆失败，手机号或验证码错误");
        }
      }
    },
    onFailed(error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: "top",
        });
      }
    },
    //发送验证码
    async onSendSms() {
      try {
        await this.$refs["login-form"].validate("mobile")
        // 开启发送验证码按钮的loading状态，防止网络慢用户D多次点击
        this.issendSmsLoading = true
        await sendSms(this.user.mobile);
        this.iscountDownshow =true
      } catch (err) {
        let message = "";
        if (err && err.response && err.response.status === 429) {
          // 发送短信失败的错误提示
          message = "发送太频繁，请稍后再试";
        } else if (err.name === "mobile") {
          // 表单验证失败的错误提示
          message = err.message;
        } else {
          // 未知错误
          message = "发送失败，请稍后再试";
        }
        //提示用户
        this.$toast({
          message,
          position: "top",
        });
      }
        //无论发送验证码成功还是失败，最后都要关闭发送按钮的loading状态
      this.issendSmsLoading = false
    },
  },
};
</script>

<style lang="less" scoped>
.login-container {
  .send-btn {
    width: 78px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .login-btn-wrap {
    // margin-top: 20px;
    padding: 26px 16px;
    .login-btn {
      border: none;
      background-color: #6db4fb;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>